/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewJApplet.java
 *
 * Created on Nov 8, 2010, 1:46:32 PM
 */

/**
 *
 * @author Pablo Ricardo Fernandez da Silva
 */

import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;

import java.awt.*;
import java.awt.event.*;
import javax.swing.GroupLayout.*;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UIManager.*;
import javax.swing.border.TitledBorder;
import java.util.Arrays.*;
import java.util.Collections;

import com.sun.java.swing.plaf.windows.*;
import com.sun.java.swing.plaf.nimbus.*;


public class BookCentre extends JApplet implements ActionListener {
	public BookCentre() {
	}
	
	// first place were methods are called
	public void init () {
		setLookAndFeel ();
		initComponents ();        
		}
	
	//Change the LookAndFeelInfo manager, tries to use Nimbus if not available uses the default
	
    private void setLookAndFeel () {
    	
    	try {
    		for ( LookAndFeelInfo info : UIManager.getInstalledLookAndFeels() ) {
    			if ("Nimbus".equals(info.getName())) {
    				UIManager.setLookAndFeel(info.getClassName());
    			}
    		}
    		
    		
    		//UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); 
                  //MetalLookAndFeel.setCurrentTheme(new OceanTheme());
                  //UIManager.setLookAndFeel(new MetalLookAndFeel()); 
                
    	}catch ( Exception e ) {
			e.printStackTrace();
		}	   
	}
   

	public void actionPerformed ( ActionEvent e ) {
		
		// When the submit button on the Input JPanel is press these actions are performed
		if ( e.getSource()==inputBtnSubmit ) {
			
			setCustomerInformation(getCustomerName(), getCustomerBooks()); // Sends the Customer name and books the customer picks 
			
		}

		// When the Display JPanel is select these actions are performed
		if ( e.getSource() == menu_BtnDisplay ) {
			setCardLayout("display");
			setDisplay_TextArea();
		}
		
		// When the submit button on the Processing JPanel is press these actions are performed
		if ( e.getSource() == process_BtnSubmit ) {
			
			setProcessingComboBox();
		}
		
		if ( e.getSource()==menu_BtnInput ){
			setCardLayout("input");
			inp_Tfd1.grabFocus();
		}
			
		if ( e.getSource()==menu_BtnProcessing){
			setCardLayout("processing");
			process_CbBox.removeAllItems();
			for (int i=0;i<customerCount;i++){
				process_CbBox.addItem(array[i].getName());
			}
		}
	}
	
	public void setCardLayout(String panel) {
		cardLayout.show( main_Panel, panel );
	}

	public void setProcessingComboBox() {
		int index = process_CbBox.getSelectedIndex();
		
		for ( int i =0;i<3;i++ ) {
				if ( process_Acc[i].isSelected() ){
					array[index].setShipment(i);
				}
				else {
					array[index].removeShipment(i);
				}
		}
	}

	public void setDisplay_TextArea(){
		
		setClearChoices(2); // Clean the 
		
		Customer[] array3 = new Customer[100];
		array3= getBubbleSortAlphabeticOrder();
		
		
		for ( int i = 0 ; i< customerCount ; i++ ) {
			display_TextArea1.append( array3[i].toString() + "\n" );
		}
	}
	
	public String[] getCustomerBooks (){
		
		String [] customerBooks = {"","",""};
		
		int[] index = inputJlist1.getSelectedIndices();
		
		if(index.length == 3){ //Checks if the customer pick 3 books exactly  
			for (int i = 0; i < index.length; i++) {
				customerBooks[i] = (String) inputJlist1.getModel().getElementAt(index[i]); //get the 3 books selected and pass 
				                                                                            //to the Array of strings
			}
		}
		return customerBooks;
	}
	
	public String getCustomerName(){
		
		String customerName = "";
		customerName = inp_Tfd1.getText();
		
		return customerName;
	}
			
	public void getErrorMessages (int messages){
		switch(messages){
        case 1:
        	// Send a message of warning asking the customer to fill out his name
        	JOptionPane.showMessageDialog(input_Panel, "Please type the Customer's Name");
        	inp_Tfd1.grabFocus();
        	break;
        case 2:
        	// Send a message of warning asking the customer to fill out his name
        	JOptionPane.showMessageDialog(input_Panel, "select exactly three books");
        	inputJlist1.grabFocus();
        	break;
        case 3:
        	// Send a message of warning asking the customer to fill out his name
        	JOptionPane.showMessageDialog(input_Panel, "This application reached the maximum number of Customers");
        	inp_Tfd1.grabFocus();
        	break;
        	
    }
		
		
	}
	public void setCustomerInformation(String customer, String[] books){
		
		boolean  noBooks = getEmptyCustomerBooks( books ); 
		boolean  noCusto = getEmptyCustomerName( customer ) ;
		boolean  maxCust = getMaximumCustomers( customerCount );
		
		// Check if the customer fill out all fields properly  
		if( noBooks || noCusto || maxCust) {
			
			if(noBooks) {               
				getErrorMessages(2); // if the Customer didn't pick exactly 3 books
			}
			
			if(noCusto){                
				getErrorMessages(1); // If the Customer name field is empty  
			}
			
			if (maxCust){
				getErrorMessages(3); // More than 100 customers
			}
		}
		// in case all information is ok create a new customer 
		else {
			array[customerCount] = new Customer (customer, books[0],books[1],books[2]);
			customerCount++;
					
			inputLabel2.setText(Integer.toString(customerCount) + " Customers out of 100 Entered");
			
			setClearChoices(1);
			inp_Tfd1.grabFocus();
		}
	}
	
	public boolean getMaximumCustomers(int count){
		boolean max = false;
	 
		if ( customerCount == 100 ){
				max = true;
		}
			return max;
	}
	
	// check if the Customer typed his name
	public boolean getEmptyCustomerName(String name){
		boolean empty = false;
	 
		if ( name.isEmpty() ){
				empty = true;
		}
			return empty;
	}
	
	//checks if the customer pick 3 books
	public boolean getEmptyCustomerBooks(String[] books){
		boolean empty = false;
 
		for (int i=0;i < 3;i++){
			if (books[i].isEmpty()){	
			empty = true;
			break;
			}
		}
			return empty;
	}
	
	// Bubble Sort nested loop method
	public Customer[] getBubbleSortAlphabeticOrder ( )  {
		  
		Customer[] array2 = array.clone();
		Customer hold=null; 
		int count = customerCount -1;
		
		for ( int i = 0; i <= count; i++ ) {
			for ( int j = count; j > i; j-- ) {
				if ( array2[j].getName().compareToIgnoreCase( array2[j-1].getName())<0 ){ 
				  hold = array2[j];        
			      array2[j] = array2[j-1]; 
			      array2[j-1] = hold;
				} 
		
	    	}    	
		}
		return array2;
	}
	public void setClearChoices(int choice){
		
		switch(choice){
		case 1:
			inp_Tfd1.setText("");
			inputJlist1.clearSelection();
			break;
		case 2:
			display_TextArea1.setText( "" );
			break;
		}
	}
    
	public JPanel getInputPanel(){
		
		
		inputBtnSubmit.addActionListener(this);
        input_Panel.setBorder(javax.swing.BorderFactory.createTitledBorder("Customer Information "));
        
     // Input Panel and components settings
        input_Panel.setLayout(inp_Grl);
        inputLabel2.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        inp_Tfd1.setColumns(30);
        inp_Jsp1.setMaximumSize(new Dimension(280, 50));
        inp_Tfd1.setMaximumSize(new Dimension(280, 50));
       // input_Panel.add(inputLabel1);
        
     // Uses Group Layout Manager on Input Pane 
        
        inp_Grl.setHorizontalGroup(
        	inp_Grl.createParallelGroup(Alignment.LEADING)
        		.addGroup(inp_Grl.createSequentialGroup()
        			.addGap(30)
        			.addGroup(inp_Grl.createParallelGroup(Alignment.LEADING)
        				.addGroup(inp_Grl.createSequentialGroup()
        					.addComponent(inputLabel2, GroupLayout.PREFERRED_SIZE, 203, GroupLayout.DEFAULT_SIZE))
        					
        					
        					
        				.addGroup(inp_Grl.createSequentialGroup()
        					.addGroup(inp_Grl.createParallelGroup(Alignment.LEADING)
        						.addComponent(inputLabel5)
        						.addComponent(inputLabel3)
        						.addComponent(inputLabel4))
        					.addGap(18)
        					.addGroup(inp_Grl.createParallelGroup(Alignment.LEADING)
        						.addComponent(inputBtnSubmit)
        						.addComponent(inp_Tfd1, GroupLayout.DEFAULT_SIZE, 150, GroupLayout.DEFAULT_SIZE)
        						.addComponent(inp_Jsp1, GroupLayout.DEFAULT_SIZE, 150, GroupLayout.DEFAULT_SIZE))))
        			.addGap(63))
        );
        
        inp_Grl.setVerticalGroup(
        	inp_Grl.createParallelGroup(Alignment.LEADING)
        		.addGroup(inp_Grl.createSequentialGroup()
        			.addGap(60)
        			.addGroup(inp_Grl.createParallelGroup(Alignment.BASELINE)
        				.addComponent(inputLabel2))
        			.addGap(60)
        			.addGroup(inp_Grl.createParallelGroup(Alignment.LEADING)
        				.addComponent(inp_Tfd1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(inputLabel4))
        			.addGap(60)
        			.addPreferredGap(ComponentPlacement.UNRELATED)
        			.addGroup(inp_Grl.createParallelGroup(Alignment.BASELINE)
        				.addGroup(inp_Grl.createSequentialGroup()
        					.addComponent(inputLabel3)
        					.addGap(9)
        					.addComponent(inputLabel5))
        				.addComponent(inp_Jsp1, GroupLayout.PREFERRED_SIZE, 99, GroupLayout.PREFERRED_SIZE))
        			.addGap(60)
        			.addComponent(inputBtnSubmit)
        			.addContainerGap(112, Short.MAX_VALUE))
        );
       
        return input_Panel;
	}
	
	
	public JPanel getProcessingPanel(){
		
		for (int j = 0; j < 3; j++) {

		      proc_Rdg[j] = new ButtonGroup();

		      process_Acc[j] = new JRadioButton("Can be shipped ", false);
		      process_Acc[j].addActionListener(this);
		      process_Rej[j] = new JRadioButton("Shipment delayed ", true);
		      process_Rej[j].addActionListener(this);
		      
		      proc_Rdg[j].add(process_Acc[j]);
		      proc_Rdg[j].add(process_Rej[j]);
		}
				
		// Create the components for processing Panel
		
		
        process_BtnSubmit.addActionListener(this);
        process_CbBox.setMaximumSize(getMaximumSize());
        
        
        
        // Processing Panel and components settings
        processing_Panel.setLayout(gl_processing);
        processing_Panel.add(process_CbBox);
        
        processing_Panel.setBorder(javax.swing.BorderFactory.createTitledBorder("Change Shippment Scheculed"));
        
		// create Panels and Container
        process_Lbl1.setFont(new java.awt.Font("Arial",1, 14));
        
        process_CbBox.addItemListener(
        		new ItemListener(){

					
					public void itemStateChanged(ItemEvent event) {
						int index = 0;
						if(event.getStateChange()==ItemEvent.SELECTED)
							index=process_CbBox.getSelectedIndex();
							//JOptionPane.showMessageDialog(null,"ok");
							
							process_Lbl2.setText(array[index].getBook(1));
							process_Lbl3.setText(array[index].getBook(2));
							process_Lbl1.setText(array[index].getBook(0));
							for(int i=0;i<3;i++){
								
								if((array[index].getShipment(i))){
									proc_Rdg[i].setSelected((process_Acc[i].getModel()),true);
								}else {
									proc_Rdg[i].setSelected((process_Rej[i].getModel()),true);
								}
							}
						}
        			
        		});
        
     // Uses Group Layout Manager on Processing Pane
        
        gl_processing.setHorizontalGroup(
        	gl_processing.createParallelGroup(Alignment.LEADING)
        		.addGroup(Alignment.TRAILING, gl_processing.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(gl_processing.createParallelGroup(Alignment.TRAILING)
        				.addComponent(process_CbBox, Alignment.LEADING, 0, 3, Short.MAX_VALUE)
        				.addGroup(gl_processing.createSequentialGroup()
        					.addGroup(gl_processing.createParallelGroup(Alignment.LEADING)
        						.addComponent(process_Lbl1)
        						.addComponent(process_Lbl2)
        						.addComponent(process_Lbl3))
        						.addGap(40)
        					.addGroup(gl_processing.createParallelGroup(Alignment.LEADING)
        						.addComponent(process_Acc[0])
        						.addComponent(process_Acc[1])
        						.addComponent(process_Acc[2])
        						.addComponent(process_BtnSubmit))
        					.addGap(40)
        						.addGroup(gl_processing.createParallelGroup(Alignment.LEADING)
        						.addComponent(process_Rej[0])
        						.addComponent(process_Rej[1])
        						.addComponent(process_Rej[2]))
        					.addGap(40))))
        				);
        gl_processing.setVerticalGroup(
        	gl_processing.createParallelGroup(Alignment.LEADING)
        		.addGroup(gl_processing.createSequentialGroup()
        			.addContainerGap()
        			.addComponent(process_CbBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        			.addGap(80)
        			.addGroup(gl_processing.createParallelGroup(Alignment.TRAILING)
        				.addGroup(gl_processing.createSequentialGroup()
        					.addGroup(gl_processing.createParallelGroup(Alignment.BASELINE)
        							.addComponent(process_Lbl1)
        							.addComponent(process_Acc[0])
                				    .addComponent(process_Rej[0]))
        					.addGap(80)
        					.addGroup(gl_processing.createParallelGroup(Alignment.BASELINE)
        						.addComponent(process_Lbl2)
        						.addComponent(process_Acc[1])
                				.addComponent(process_Rej[1]))
        					.addGap(80)
        					.addGroup(gl_processing.createParallelGroup(Alignment.BASELINE)
        						.addComponent(process_Lbl3)
        						.addComponent(process_Acc[2])
                				.addComponent(process_Rej[2]))
        						//.addComponent((Component) proc_Rdg[0].getElements()))
        					.addGap(80)
        					.addGroup(gl_processing.createParallelGroup(Alignment.BASELINE)
        						.addComponent(process_BtnSubmit))	
        				.addContainerGap(80, Short.MAX_VALUE)))));

        
		return processing_Panel;
	}
	
	
	
	
	public void initComponents() {
  
		
		
        
        // Create the components for Menu Panel
        menu_BtnInput.addActionListener(this);
        menu_BtnDisplay.addActionListener(this);
        menu_BtnProcessing.addActionListener(this);
        
        // Create the components for display Panel
        // Container and components settings
        c.add(menu_Panel, BorderLayout.WEST);
        c.add(main_Panel, BorderLayout.CENTER);
        
        // Menu Panel and components settings
        menu_Panel.setLayout(new GridLayout(3,1));
        menu_Panel.add(menu_BtnInput);
        menu_Panel.add(menu_BtnProcessing);
        menu_Panel.add(menu_BtnDisplay);
        
        main_Panel.add(empty,"empty");
        main_Panel.add(getInputPanel(),"input");
        main_Panel.add(getProcessingPanel(),"processing");
        main_Panel.add(display_Panel,"display");

        // Display Panel and components settings
        display_Panel.setLayout(new BorderLayout());
        display_TextArea1.setRows(500);
        
        display_TextArea1.setWrapStyleWord(true);
        display_TextArea1.setFont(new java.awt.Font("Serif", Font.ITALIC, 12));
        display_TextArea1.setEditable(false);
       
        display_Panel.add(scrollPane);
		display_Panel.add(scrollPane, BorderLayout.CENTER);
        display_Panel.add(display_Label1, BorderLayout.NORTH);
        
        display_Panel.setBorder(javax.swing.BorderFactory.createTitledBorder("Customer report"));
  }

	
	// Variables declaration 
	private JButton menu_BtnInput = new JButton("Input");
    private JButton menu_BtnProcessing = new JButton("Processing");
    private JButton menu_BtnDisplay = new JButton("Display");
    private JButton inputBtnSubmit = new JButton("Submit");;
    private JLabel inputLabel2 = new JLabel(Integer.toString(customerCount) + " Customers out of 100 Entered");
    private JLabel inputLabel3 = new JLabel("Choose exactly three books:" );
    private JLabel inputLabel4 = new JLabel("Customer Name:");
    private JLabel inputLabel5 = new JLabel("Use CTRL or SHIFT");
    private static int customerCount=0;
    private JTextField inp_Tfd1 = new JTextField();
    private JLabel process_Lbl1 = new JLabel("empty");    
    private JLabel process_Lbl2 = new JLabel("empty");
    private JLabel process_Lbl3 = new JLabel("empty");
    private JComboBox process_CbBox = new JComboBox();
    private ButtonGroup[] proc_Rdg = new ButtonGroup[3];
    private JRadioButton[] process_Acc= new JRadioButton[3];
	private JRadioButton[] process_Rej= new JRadioButton[3];
    private JButton process_BtnSubmit = new JButton("Submit");
    private JPanel processing_Panel = new JPanel();
    private GroupLayout gl_processing = new GroupLayout(processing_Panel);
    private JTextArea display_TextArea1 = new JTextArea();
    private JScrollPane scrollPane = new JScrollPane(display_TextArea1);
    private JLabel display_Label1 = new JLabel("List of Customers and Orders Status");
    private Container c = this.getContentPane();
    private CardLayout cardLayout = new CardLayout();
    private JPanel menu_Panel = new JPanel();
    private JPanel main_Panel = new JPanel(cardLayout);
    private JPanel empty = new JPanel();
    private JPanel input_Panel = new JPanel();
    private JPanel display_Panel = new JPanel();
    private String[] books = { "Deitel-Java How to Program ", 
    "Horstmann-Big Java ", "Lewis-Software Solutions", "Staugaard-Java for IS ", 
    "Sun-Core Java", "Hamilton-JDBC", "Jackson-Java By Example", 
    "Riley-The Object of Java", "Geary-Graphic Java", "Santry-Advanced Java2", 
    "Bishop-Java Gently ", "Wigglesworth-Advanced Java", "Liang-intro to Java", 
    "Lambert-Java" };
    private JList inputJlist1 = new JList(books);
    private Customer[] array = new Customer[100];
    private JScrollPane inp_Jsp1= new JScrollPane(inputJlist1);
    private GroupLayout inp_Grl = new GroupLayout(input_Panel);
    // End of the variables

}
